package com.example.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements  View.OnClickListener{

	TextView responseText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest=(Button)findViewById(R.id.send_request);
        responseText=(TextView)findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    }
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId()==R.id.send_request){
			sendRequestWithHttpURLConnection();
		}
	}
	private void sendRequestWithHttpURLConnection() {
		// TODO Auto-generated method stub
		new Thread(new Runnable(){
			public void run(){
				HttpURLConnection connection=null;
				BufferedReader reader=null;
				try{
					URL url=new URL("http://www.baidu.com");
					connection=(HttpURLConnection)url.openConnection();
					connection.setRequestMethod("GET");
					connection.setConnectTimeout(8000);
					connection.setReadTimeout(8000);
					InputStream in=connection.getInputStream();
					reader= new BufferedReader(new InputStreamReader(in));
					StringBuilder response=new StringBuilder();
					String line;
					while((line=reader.readLine())!=null){
						response.append(line);
					}
						showResponse(response.toString());
					
					
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}finally{
					if(reader!=null){
						try{
							reader.close();
						}catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
						}
					}
					if(connection!=null){
						connection.disconnect();
					}
				}
			}

			
		}).start();
	}

	private void showResponse(final String response) {
		// TODO Auto-generated method stub
		runOnUiThread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				responseText.setText(response);
			}
			
		});
	}
    
    
}
